package com.test.multithread.servlet; /**
 * 2010-4-14 
 */  
import java.io.ByteArrayOutputStream;  
import java.io.IOException;  
import java.io.OutputStream;  
import java.util.zip.GZIPOutputStream;  
  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
/** 
 * GZip服务 
 *  
 * @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a> 
 * @since 1.0 
 */  
public class GZipServlet extends HttpServlet {  
  
    private static final long serialVersionUID = -4811926975427533081L;  
    private static final String ENCODING = "UTF-8";  
  
    /** 
     * 压缩 
     *  
     * @param data 
     * @return  
     * @throws Exception 
     */  
    private byte[] compress(byte[] data) throws Exception {  
  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  
        // 压缩  
        GZIPOutputStream gos = new GZIPOutputStream(baos);  
  
        gos.write(data, 0, data.length);  
  
        gos.finish();  
  
        byte[] output = baos.toByteArray();  
  
        baos.flush();  
        baos.close();  
  
        return output;  
    }  
  
    /** 
     * @param request 
     * @param response 
     * @throws ServletException 
     * @throws IOException 
     */  
    private void excute(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
  
        byte[] data = "我是一个中国人！".getBytes(ENCODING);  
  
        try {  
            byte[] output = compress(data);  
  
            // 设置Content-Encoding，这是关键点！  
            response.setHeader("Content-Encoding", "gzip");  
            // 设置字符集  
            response.setCharacterEncoding(ENCODING);  
            // 设定输出流中内容长度  
            response.setContentLength(output.length);  
  
            OutputStream out = response.getOutputStream();  
            out.write(output);  
            out.flush();  
            out.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
  
    /** 
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse 
     *      response) 
     */  
    protected void doGet(HttpServletRequest request,  
            HttpServletResponse response) throws ServletException, IOException {  
        excute(request, response);  
    }  
  
    /** 
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 
     *      response) 
     */  
    protected void doPost(HttpServletRequest request,  
            HttpServletResponse response) throws ServletException, IOException {  
        excute(request, response);  
    }  
  
}  